import { statusOptions } from "@/data/wbsData.ts";
import { priorityColors, statusColors } from "@/components/CLTable/register";
import { moreIcon, selectIcon } from "@/utils/SvgIcons.ts";
import * as VTable from "@visactor/vtable";
interface RendererContext {
  args: any;
  tableLib: any;
  props?: any;
  options?: any;
  tableField?: string;
  field?: any;
}
type Renderer = (ctx: RendererContext) => {
  rootContainer: any;
  renderDefault: boolean;
};

const rendererMap: Record<string, Renderer> = {
  operations: ({ args, props, options }) => {
    const { table, row, col, rect } = args;
    const { height, width } = rect || table.getCellRect(col, row);

    // 如果是文字模式
    if (props?.tableConfig?.OperationsColumnMode === "text") {
      const container = new VTable.CustomLayout.Group({
        opacity: 0.1,
        width,
        height,
        display: "flex",
        flexWrap: "wrap",
        justifyContent: "flex-start",
        alignItems: "center",
      });

      props.moreActions?.forEach(
        (action: {
          key: string;
          label: string;
          disabled?: any;
          invisible?: any;
        }) => {
          const record = props.initialData[args.row - 1];
          let show = true;
          if (action.disabled && Array.isArray(action.disabled)) {
            show = !action.disabled.some((field: string) => record[field]);
          }
          let visible = true;
          if (action.invisible && Array.isArray(action.invisible)) {
            visible = !action.invisible.some((field: string) => record[field]);
          }
          if (visible) {
            const text = getDisplayLabel(action, record);
            const color = getDisplayColor(action, record) || "#333";
            const tag = new VTable.CustomLayout.Tag({
              text: text,
              textStyle: {
                fontSize: 13,
                fontFamily: "sans-serif",
                fill: show ? color : "#dad0d0",
                cursor: show ? "pointer" : "not-allowed",
              },
              panel: {
                visible: true,
                lineWidth: 1,
                cornerRadius: 8,
                fill: "rgba(255,255,255,0.01)",
              },
              boundsPadding: [0, 0, 0, 10],
              padding: [3, 6],
              pickable: true,
              fillPickable: true,
              strokePickable: true,
              childrenPickable: true,
              pickMode: "imprecise",
            });

            tag.addEventListener("click", (e: any) => {
              e.stopPropagation();
              options?.onActionClick?.(action.key, row);
            });
            tag.addEventListener("mouseenter", () => {
              tag.setAttributes({
                textStyle: {
                  ...tag.attribute.textStyle,
                  fill: show ? "#409EFF" : "#333",
                },
              });
              options?.onNeedRender?.();
            });
            tag.addEventListener("mouseleave", () => {
              if (!show) return;
              tag.setAttributes({
                textStyle: { ...tag.attribute.textStyle, fill: color },
              });
              options?.onNeedRender?.();
            });

            (container as any).add(tag);
          }
        },
      );

      return { rootContainer: container, renderDefault: false };
    }

    if (props?.tableConfig?.OperationsColumnMode === "textIcon") {
      const container = new VTable.CustomLayout.Group({
        opacity: 0.1,
        width,
        height,
        display: "flex",
        flexWrap: "wrap",
        justifyContent: "flex-start",
        alignItems: "center",
      });

      props.moreActions?.forEach(
        (action: {
          key: string;
          label: string;
          disabled?: any;
          invisible?: any;
        }) => {
          const record = props.initialData[args.row - 1];
          let show = true;
          if (action.disabled && Array.isArray(action.disabled)) {
            show = !action.disabled.some((field: string) => record[field]);
          }
          let visible = true;
          if (action.invisible && Array.isArray(action.invisible)) {
            visible = !action.invisible.some((field: string) => record[field]);
          }
          if (visible) {
            const text = getDisplayLabel(action, record);
            const color = getDisplayColor(action, record) || "#333";
            const tag = new VTable.CustomLayout.Tag({
              text: text,
              textStyle: {
                fontSize: 13,
                fontFamily: "sans-serif",
                fill: show ? color : "#dad0d0",
                cursor: show ? "pointer" : "not-allowed",
              },
              panel: {
                visible: true,
                lineWidth: 1,
                cornerRadius: 8,
                fill: "rgba(255,255,255,0.01)",
              },
              boundsPadding: [0, 0, 0, 10],
              padding: [3, 6],
              pickable: true,
              fillPickable: true,
              strokePickable: true,
              childrenPickable: true,
              pickMode: "imprecise",
            });

            tag.addEventListener("click", (e: any) => {
              if (!show) return;
              e.stopPropagation();
              options?.onActionClick?.(action.key, row);
            });
            tag.addEventListener("mouseenter", () => {
              tag.setAttributes({
                textStyle: {
                  ...tag.attribute.textStyle,
                  fill: show ? "#409EFF" : "#dad0d0",
                },
              });
              options?.onNeedRender?.();
            });
            tag.addEventListener("mouseleave", () => {
              // if (!show) return;
              tag.setAttributes({
                textStyle: {
                  ...tag.attribute.textStyle,
                  fill: show ? color : "#dad0d0",
                },
              });
              options?.onNeedRender?.();
            });

            (container as any).add(tag);
          }
        },
      );

      return { rootContainer: container, renderDefault: false };
    }

    // 图标模式
    const container = new VTable.CustomLayout.Group({
      width,
      height,
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
    }); // 更多操作图标
    const more = new VTable.CustomLayout.Icon({
      svg: moreIcon,
      width: 14,
      height: 10,
      cursor: "pointer",
    });
    (container as any).add(more);
    more.addEventListener("click", (e: any) => {
      e.stopPropagation();
      if (!options?.hasAvailableActions?.()) {
        return;
      } // 获取点击位置
      const rect = table.getCellRect(col, row);
      const tableRect = table?.container?.getBoundingClientRect?.();
      const bounds = rect?.bounds;
      if (rect && tableRect && bounds) {
        const leftPos =
          (tableRect.left || 0) +
          (bounds.x1 || 0) +
          (rect.width || 0) -
          20 +
          (window.scrollX || 0);
        const topPos =
          (tableRect.top || 0) +
          (bounds.y1 || 0) +
          (rect.height || 0) / 2 +
          (window.scrollY || 0);
        const popupWidth = 160;
        const popupHeight = 200;
        let adjustedLeft = leftPos - 140;
        let adjustedTop = topPos - 20;
        if (adjustedLeft + popupWidth > window.innerWidth) {
          adjustedLeft = window.innerWidth - popupWidth - 10;
        }
        if (adjustedLeft < 0) {
          adjustedLeft = 10;
        }
        if (adjustedTop + popupHeight > window.innerHeight) {
          adjustedTop = window.innerHeight - popupHeight + 20;
        }
        if (adjustedTop < 0) {
          adjustedTop = 10;
        }
        const popupPosition = { left: adjustedLeft, top: adjustedTop }; // 交给外部处理
        options?.onMoreClick?.({
          record: table.getRecordByRowCol(col, row),
          row,
          col,
          popupPosition,
        });
      }
    });

    return { rootContainer: container, renderDefault: false };
  },
  single: ({ args, tableLib, tableField, options, field }) => {
    const { table, row, col, rect } = args;
    const { height, width } = rect || table.getCellRect(col, row);
    const record = table.getRecordByRowCol(col, row) || {};
    let statusText =
      tableField && record[tableField] !== undefined ? record[tableField] : "";
    let backgroundColor, image, color;
    const fieldOptions = Array.isArray(field.options)
      ? field.options
      : field.options != null
        ? [field.options]
        : [];
    let option;
    if (fieldOptions.length > 0)
      option = fieldOptions.find(
        (option: any) => option.code === String(statusText),
      );
    if (!option && fieldOptions.length > 0) {
      option = fieldOptions.find((option: any) => option.code === "null");
    }
    statusText = option?.name;
    color = option?.color ?? "#333";
    backgroundColor = option?.backgroundColor ?? "#fff";
    image = selectIcon
      .replace(/<path d="M12 23[^>]+><\/path>/, "")
      .replace(/currentColor/g, color);
    if (tableField === "taskStatus") {
      statusText = record.lifecycleCurrentNode?.name.zh_CN ?? "";
    }
    const container = new tableLib.Group({
      width,
      height,
      display: "flex",
      alignItems: "center",
      flexDirection: "row",
      justifyContent: "center",
    });

    const content = new tableLib.Group({
      width: width - 25,
      height: 22,
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      cornerRadius: 4,
      fill: backgroundColor,
      cursor: "pointer",
      opacity: 0.3,
    });

    const text = new tableLib.Text({
      text: statusText,
      fontSize: 12,
      fill: color,
      textAlign: "center",
      textBaseline: "middle",
      boundsPadding: [0, 0, 0, 10],
      maxLineWidth: width - 65,
      ellipsis: true,
    });

    const arrow = new tableLib.Image({
      image,
      width: 16,
      height: 16,
      boundsPadding: [0, 10, 0, 0],
    });

    (content as any).add(text);
    (content as any).add(arrow);
    (container as any).add(content);

    let clickCount = 0;
    let clickTimer: any = null;
    container.addEventListener("click", (e: MouseEvent) => {
      e.stopPropagation();
      clickCount++;
      if (clickCount === 1) {
        clickTimer = setTimeout(() => {
          // 单击逻辑（如果需要）
          clickCount = 0;
        }, 300); // 300ms 内再次点击视为双击
      } else if (clickCount === 2) {
        clearTimeout(clickTimer);
        if (tableField === "taskStatus") {
          const rect = table.getCellRect(col, row);
          const tableRect = table?.container?.getBoundingClientRect?.();
          const bounds = rect?.bounds;
          console.log("rect", tableRect, bounds);
          if (rect && tableRect && bounds) {
            const scrollLeft = table.getScrollLeft ? table.getScrollLeft() : 0;
            const scrollTop = table.getScrollTop ? table.getScrollTop() : 0;

            // const cellWidth = bounds.x2 - bounds.x1;
            // const cellHeight = bounds.y2 - bounds.y1;

            // 取单元格的左下角位置（更符合 UI 预期）
            const cellLeftX = bounds.x1 - scrollLeft;
            const cellBottomY = bounds.y2 - scrollTop;

            // 转换为屏幕坐标
            const leftPos = tableRect.left + cellLeftX + window.scrollX;
            const topPos = tableRect.top + cellBottomY + window.scrollY;

            // 偏移控制（可调节）
            const popupOffsetX = 0; // 弹窗紧贴单元格左侧，可调负数往左
            const popupOffsetY = 6; // 弹窗与单元格下缘间距

            const popupPosition = {
              left: leftPos + popupOffsetX,
              top: topPos + popupOffsetY,
            };
            // console.log("popupPosition", popupPosition);
            options?.onActionClick?.(record, popupPosition);
            clickCount = 0;
          }
        } else {
          options?.onActionClick?.("selectNode", record);
        }
      }
    });

    return { rootContainer: container, renderDefault: false };
  },
  multiple: ({ args, tableLib, field }) => {
    const { table, row, col, rect } = args;
    const { height, width } = table.getCellRect(col, row);
    const record = table.getRecordByRowCol(col, row) || {};
    const container = new tableLib.Group({
      width,
      height,
      display: "flex",
      flexWrap: "wrap",
      justifyContent: "flex-start",
      alignItems: "center",
    });

    const containerContent = new tableLib.Group({
      opacity: 0.1,
      width: width,
      height: 22,
      display: "flex",
      flexWrap: "wrap",
      justifyContent: "flex-start",
      alignItems: "center",
    });
    record?.[field.field]?.length &&
      record[field.field].map((str: string) => {
        const tag = new VTable.CustomLayout.Tag({
          text: str,
          textStyle: {
            fontSize: 12,
            fontFamily: "sans-serif",
            fill: "#fff",
          },
          panel: {
            visible: true,
            fill: priorityColors[str],
            lineWidth: 1,
            cornerRadius: 8,
          },
          boundsPadding: [0, 0, 0, 10],
          padding: [3, 6],
        });
        (containerContent as any).add(tag);
      });

    (container as any).add(containerContent);
    return { rootContainer: container, renderDefault: false };
  },
  user: ({ args, tableLib, tableField, options, field }) => {
    const { table, row, col, dataValue } = args;
    const { height, width } = table.getCellRect(col, row);
    const record = table.getRecordByRowCol(col, row) || {};
    const avatarSize = 24;
    const gap = 4; // 头像与名字间距
    // 根容器：横向排列，垂直居中
    const container = new tableLib.Group({
      width: width / 2 + 50,
      height,
      display: "flex",
      alignItems: "center",
    });
    // console.log("dataValue", record, tableField);
    // 判断dataValue是否为数组
    if (Array.isArray(dataValue) && dataValue.length > 0) {
      // 处理多用户显示情况
      let usedWidth = 0;
      const items: any[] = [];
      // 计算每个用户项的大致宽度并检查是否会超出
      // 注意：这里使用估算值，因为没有getTextWidth函数
      const avgCharWidth = 8; // 平均字符宽度估算值

      dataValue.forEach((user: any) => {
        const userName = typeof user === "string" ? user : user.name || "";
        const userWidth = avatarSize + gap + userName.length * avgCharWidth + 8; // 8为额外间距
        if (usedWidth + userWidth <= width * 0.7) {
          // 预留30%宽度给最后可能的...
          items.push(user);
          usedWidth += userWidth;
        }
      });

      // 渲染每个用户项
      items.forEach((user: any, index: number) => {
        const userName = typeof user === "string" ? user : user.name || "";
        const shortName = shortNameOf(userName);
        const bg = stringToColor(userName || "unknown");
        const fg = pickReadableColor(bg);
        const chineseRegex = /[\u4e00-\u9fa5]/;

        // 用户项容器
        const userItem = new tableLib.Group({
          display: "flex",
          alignItems: "center",
          marginRight: index < items.length - 1 ? 8 : 0,
          marginLeft: 10,
        });

        // 头像容器
        const avatarContainer = new tableLib.Group({
          width: avatarSize,
          height: avatarSize,
        });
        // 圆形背景
        const avatarBg = new tableLib.Rect({
          width: avatarSize,
          height: avatarSize,
          fill: bg,
          cornerRadius: avatarSize / 2,
        });

        // 圆中文字
        const avatarText = new tableLib.Text({
          text: shortName,
          fontSize: chineseRegex.test(shortName)
            ? Math.floor(avatarSize * 0.4)
            : Math.floor(avatarSize * 0.6),
          fontWeight: "400",
          fill: fg,
          textAlign: "center",
          textBaseline: "middle",
          x: avatarSize / 2,
          y: avatarSize / 2,
        });

        // 名字文本
        const nameText = new tableLib.Text({
          text: userName,
          fontSize: 14,
          fill: "#333",
          textBaseline: "middle",
          marginLeft: gap,
        });

        avatarContainer.add(avatarBg);
        avatarContainer.add(avatarText);
        userItem.add(avatarContainer);
        userItem.add(nameText);
        container.add(userItem);
      });

      // 如果有超出的用户，显示省略号
      if (dataValue.length > items.length) {
        const ellipsis = new tableLib.Text({
          text: `+${dataValue.length - items.length}`,
          fontSize: 14,
          fill: "#333",
          textBaseline: "middle",
          marginLeft: 8,
        });
        container.add(ellipsis);
      }
    } else if (tableField && record[tableField] !== undefined) {
      // 处理单用户显示情况（保持原有逻辑）
      const avatarValue = tableField ? record[tableField] : "";
      if (!avatarValue) {
        return { rootContainer: container, renderDefault: false };
      }
      let name =
        typeof avatarValue === "string" ? avatarValue : avatarValue.name || "";
      const shortName = shortNameOf(name);
      const bg = stringToColor(name || "unknown");
      const fg = pickReadableColor(bg);
      const chineseRegex = /[\u4e00-\u9fa5]/;

      // containerContent：用于把圆背景和文本叠在一起
      const containerContent = new tableLib.Group({
        width: avatarSize,
        height: avatarSize,
        marginLeft: 6,
      });

      // 圆形背景
      const avatarBg = new tableLib.Rect({
        width: avatarSize,
        height: avatarSize,
        fill: bg,
        cornerRadius: avatarSize / 2,
        boundsPadding: [0, gap, 0, gap],
      });

      // 圆中文字
      const avatarText = new tableLib.Text({
        text: shortName,
        fontSize: chineseRegex.test(shortName)
          ? Math.floor(avatarSize * 0.4)
          : Math.floor(avatarSize * 0.6),
        fontWeight: "400",
        fill: fg,
        textAlign: "center",
        textBaseline: "middle",
        x: avatarSize / 2,
        y: avatarSize / 2,
      });

      // 名字文本
      const text = new tableLib.Text({
        text: name,
        fontSize: 14,
        fill: "#333",
        textBaseline: "middle",
        y: height / 2,
        maxLineWidth: width - avatarSize - 20,
        ellipsis: "...",
      });

      containerContent.add(avatarBg);
      containerContent.add(avatarText);
      container.add(containerContent);
      container.add(text);
    }

    // 点击事件处理（保持原有逻辑）
    let clickCount = 0;
    let clickTimer: any = null;

    container.addEventListener("click", (e: any) => {
      e.stopPropagation();
      clickCount++;

      if (clickCount === 1) {
        clickTimer = setTimeout(() => {
          // 单击逻辑（如果需要）
          clickCount = 0;
        }, 300); // 300ms 内再次点击视为双击
      } else if (clickCount === 2) {
        clearTimeout(clickTimer);
        const cellinfo = table.getCellInfo(col, row);
        record._fieldName = cellinfo.field;
        options?.onActionClick?.("userSelector", record);
        clickCount = 0;
      }
    });

    return { rootContainer: container, renderDefault: false };
  },
  selectUser: ({ args, tableLib, tableField, options, field }) => {
    // console.log("args", args, tableLib, tableField, options, field);
    return rendererMap.user({ args, tableLib, tableField, options, field });
  },
  progress: ({ args, tableLib }) => {
    const { table, row, col, rect } = args;
    const { height, width } = table.getCellRect(col, row);
    const record = table.getRecordByRowCol(col, row) || {};
    let progressValue = record.progress || 0;
    const barHeight = 4;
    const maxBarWidth = width - 52;
    const valueWidth = Math.round(maxBarWidth * (progressValue / 100));
    if (typeof progressValue !== "number") progressValue = 0;
    let bgBar, progressBar;
    // 根容器
    const container = new tableLib.Group({
      width,
      height,
      display: "flex",
      alignItems: "center",
      flexDirection: "row",
    });
    const blankContainer = new tableLib.Group({
      height: barHeight,
      width: 10,
    });

    const blankTxtyContainer = new tableLib.Group({
      height: barHeight,
      width: 4,
    });
    // 进度条容器
    const containerContent = new tableLib.Group({
      height: barHeight,
      width: maxBarWidth,
    });

    // 背景条
    bgBar = new tableLib.Rect({
      width: maxBarWidth,
      height: barHeight,
      fill: "#F2F2F2",
      // cornerRadius: barHeight / 2,
    });

    // 进度条
    progressBar = new tableLib.Rect({
      width: valueWidth,
      height: barHeight,
      fill: progressValue === 100 ? "#2BA471" : "#2BA471",
      // cornerRadius: barHeight / 2,
    });

    // 百分比文本
    const text = new tableLib.Text({
      text: `${progressValue}%`,
      fontSize: 12,
      fill: "#141414",
      textAlign: "center",
      textBaseline: "middle",
    });
    // if (isGantt) {
    // }
    (container as any).add(blankContainer);
    (containerContent as any).add(bgBar);
    (containerContent as any).add(progressBar);
    (container as any).add(text);
    (container as any).add(blankTxtyContainer);
    (container as any).add(containerContent);
    return { rootContainer: container, renderDefault: false };
  },
  imagetext: ({ args, tableLib, tableField }) => {
    const { table, row, col, rect } = args;
    const { width, height } = table.getCellRect(col, row) || rect;
    const record = table.getRecordByRowCol(col, row) || {};
    const iconSize = 20;
    const gap = 6; // 图标与文字的间距
    const maxWidth = 200;

    // 用 canvas 动态计算文字宽度
    const measureTextWidth = (text: string, font = "14px sans-serif") => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      if (!ctx) return 0;
      ctx.font = font;
      return ctx.measureText(text).width;
    };
    let fileName = record[tableField] || "";
    if (typeof fileName !== "string") {
      fileName = "";
    }
    const extMatch = fileName.match(/\.([a-zA-Z0-9]+)$/);
    const ext = extMatch ? extMatch[1].toLowerCase() : "";
    // 根据扩展名选图标路径（可以改成自己的资源路径或base64）
    const extIconMap: Record<string, string> = {
      pdf: new URL("@/assets/dataReport/pdf.svg", import.meta.url).href,
      doc: new URL("@/assets/dataReport/word.svg", import.meta.url).href,
      docx: new URL("@/assets/dataReport/word.svg", import.meta.url).href,
      xls: new URL("@/assets/dataReport/excel.svg", import.meta.url).href,
      xlsx: new URL("@/assets/dataReport/excel.svg", import.meta.url).href,
      ppt: new URL("@/assets/dataReport/ppt.svg", import.meta.url).href,
      pptx: new URL("@/assets/dataReport/ppt.svg", import.meta.url).href,
      png: new URL("@/assets/dataReport/photo.svg", import.meta.url).href,
      jpg: new URL("@/assets/dataReport/photo.svg", import.meta.url).href,
      jpeg: new URL("@/assets/dataReport/photo.svg", import.meta.url).href,
      txt: new URL("@/assets/dataReport/default.svg", import.meta.url).href,
      zip: new URL("@/assets/dataReport/zip.svg", import.meta.url).href,
      rar: new URL("@/assets/dataReport/zip.svg", import.meta.url).href,
      folder: new URL("@/assets/dataReport/file.svg", import.meta.url).href,
      default: new URL("@/assets/dataReport/default.svg", import.meta.url).href,
    };
    let iconUrl = extIconMap[ext] || extIconMap["default"];
    if (record.imageUrl) iconUrl = record.imageUrl;
    const textWidth = measureTextWidth(fileName || "(无文件名)");
    const contentWidth = Math.min(iconSize + gap + textWidth + 10, maxWidth);

    // 创建容器（动态宽度）
    const container = new tableLib.Group({
      width: contentWidth,
      height,
      display: "flex",
      alignItems: "center",
    });

    // 创建图标（Image）
    const iconImage = new tableLib.Image({
      image: iconUrl,
      width: iconSize,
      height: iconSize,
      y: (height - iconSize) / 2,
      marginLeft: 18,
    });

    // 文件名文本
    const text = new tableLib.Text({
      text: fileName || "(无文件名)",
      fontSize: 14,
      fill: "#333",
      textBaseline: "middle",
      y: height / 2,
      marginLeft: gap,
      maxLineWidth: maxWidth - iconSize - gap - 20,
      ellipsis: "...",
    });

    container.add(iconImage);
    container.add(text);
    return { rootContainer: container, renderDefault: false };
  },
};
export const createStatusLayout = (
  tableField: string,
  tableType: string,
  tableLib: any,
  props?: any,
  options?: any,
  field?: any,
) => {
  return (args: any) => {
    const ctx: RendererContext = {
      args,
      tableLib,
      props,
      options,
      tableField,
      field,
    };
    const renderer = rendererMap[tableType];
    if (renderer) return renderer(ctx);
    else if (props.moreActions) {
      const renderer = rendererMap["operations"];
      return renderer(ctx);
    }
    // fallback：默认显示文本
    const { table, row, col, rect } = args;
    const { height, width } = rect || table.getCellRect(col, row);
    const record = table.getRecordByRowCol(col, row) || {};
    const textValue = String(record[tableField] || "");

    const container = new tableLib.Group({
      width,
      height,
      alignItems: "center",
      justifyContent: "center",
    });
    const text = new tableLib.Text({
      text: textValue,
      fontSize: 12,
      fill: "#333",
      textBaseline: "middle",
    });
    (container as any).add(text);

    return { rootContainer: container, renderDefault: false };
  };
};

// 头像的颜色、名字的颜色、背景色
const stringToColor = (str: string): string => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
    hash |= 0;
  }
  const c = (hash & 0x00ffffff).toString(16).toUpperCase();
  return "#" + "00000".substring(0, 6 - c.length) + c;
};

const pickReadableColor = (hex: string): string => {
  const m = (hex || "#000000").replace("#", "");
  const r = parseInt(m.substring(0, 2), 16);
  const g = parseInt(m.substring(2, 4), 16);
  const b = parseInt(m.substring(4, 6), 16);
  const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
  return lum > 0.9 ? "#000" : "#fff";
};

const shortNameOf = (name: string): string => {
  if (!name) return "";
  // 如果是中文（含汉字）
  if (/[\u4e00-\u9fa5]/.test(name)) {
    return name.slice(-2); // 最后两个字
  }
  // 如果是英文
  const parts = name.trim().split(/\s+/);
  if (parts.length === 1) {
    return parts[0].charAt(0).toUpperCase();
  } else {
    // 多个英文单词 → 取前两个单词首字母
    return parts[0].charAt(0).toUpperCase() + parts[1].charAt(0).toUpperCase();
  }
};

// 定义操作项类型
interface ActionItem {
  key: string;
  label: string | string[];
  icon?: string;
  color?: string | string[];
  switchField?: { field: string; value: string | number | boolean };
}
// 获取显示的标签文本
const getDisplayLabel = (action: ActionItem, node: any): string => {
  try {
    if (!action || !action.label) {
      return "";
    }
    if (!Array.isArray(action.label)) {
      return action.label;
    }
    // 如果有switchField且提供了有效row数据，根据条件选择label
    if (
      action.switchField &&
      node &&
      typeof node === "object" &&
      action.switchField.field in node
    ) {
      const { field, value } = action.switchField;
      const fieldValue = node[field];
      return fieldValue === value
        ? action.label[1] || ""
        : action.label[0] || "";
    } else {
      // 默认显示第一个标签
      return action.label[0] || "";
    }
  } catch (error) {
    console.error("Error in getDisplayLabel:", error);
    return action?.label?.[0] || "";
  }
};
// 获取显示的颜色
const getDisplayColor = (action: ActionItem, node: any): string => {
  try {
    if (!action) {
      return "";
    }
    if (!Array.isArray(action.color)) {
      return action.color || "";
    }
    // 如果有switchField且提供了有效row数据，根据条件选择color
    if (
      action.switchField &&
      node &&
      typeof node === "object" &&
      action.switchField.field in node
    ) {
      const { field, value } = action.switchField;
      const fieldValue = node[field];
      return fieldValue === value
        ? action.color[1] || ""
        : action.color[0] || "";
    }

    // 默认显示第一个颜色
    return action.color[0] || "";
  } catch (error) {
    console.error("Error in getDisplayColor:", error);
    return action?.color?.[0] || "";
  }
};

export enum FieldType {
  TEXT = "text",
  NUMBER = "number",
  TEXTAREA = "textarea",
  MULTIPLE = "multiple",
  SINGLE = "single",
  DATE = "date",
  CHECKBOX = "checkbox",
  IMAGE = "image",
  LINK = "link",
  SWITCH = "switch",
  USER = "user",
  SELECT_USER = "selectUser",
  PROGRESS = "progress",
  FUNCTION = "fn",
  LANGUAGE = "language",
  IMAGE_TEXT = "imagetext",
  DEFAULT = "default",
}
// 定义“同义词”映射表
const FIELD_TYPE_ALIASES: Record<string, FieldType> = {
  // 文本类
  text: FieldType.TEXT,
  textarea: FieldType.TEXT,
  string: FieldType.TEXT,
  input: FieldType.TEXT,

  // 数字类
  number: FieldType.NUMBER,
  int: FieldType.NUMBER,
  float: FieldType.NUMBER,

  // 多选
  multiple: FieldType.MULTIPLE,
  multiselect: FieldType.MULTIPLE,

  // 单选
  single: FieldType.SINGLE,
  select: FieldType.SINGLE,
  radio: FieldType.SINGLE,

  // 日期
  date: FieldType.DATE,
  datetime: FieldType.DATE,
  timestamp: FieldType.DATE,

  // 勾选
  checkbox: FieldType.CHECKBOX,
  bool: FieldType.CHECKBOX,

  // 图片
  image: FieldType.IMAGE,
  picture: FieldType.IMAGE,
  photo: FieldType.IMAGE,

  // 链接
  link: FieldType.LINK,
  url: FieldType.LINK,

  // 开关
  switch: FieldType.SWITCH,
  toggle: FieldType.SWITCH,

  // 用户
  user: FieldType.USER,
  owner: FieldType.USER,
  assignee: FieldType.USER,

  selectuser: FieldType.SELECT_USER,
  singlemember: FieldType.SELECT_USER,
  multimember: FieldType.SELECT_USER,

  // 进度
  progress: FieldType.PROGRESS,
  percent: FieldType.PROGRESS,

  // 函数类
  fn: FieldType.FUNCTION,
  function: FieldType.FUNCTION,

  //图片加文字
  imagetext: FieldType.IMAGE_TEXT,

  // 多语言
  language: FieldType.LANGUAGE,
  i18n: FieldType.LANGUAGE,
};
export const typeEnum = {
  single: ["single", "singlemember"],
  multiple: ["multiple", "multimember"],
  int: ["int"],
  float: ["float"],
};
export const getFieldType = (field: any): FieldType => {
  if (!field) return FieldType.DEFAULT;

  const key = field.toLowerCase?.().trim();
  return FIELD_TYPE_ALIASES[key] ?? FieldType.DEFAULT;
};

export const getTypeGroup = (
  type: string,
): keyof typeof typeEnum | undefined => {
  for (const key in typeEnum) {
    if (typeEnum[key as keyof typeof typeEnum].includes(type)) {
      return key as keyof typeof typeEnum;
    }
  }
  return undefined;
};
